<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<div id="app"></div>

  <script>
    function createRenderer(options){
      const {
        createElement,
        setElementText,
        insert
        
      }=options;
      function mountElement(vnode,container){
        const el=createElement(vnode.type)
       
        if(typeof vnode.children=="string"){
          setElementText(el,vnode.children);
        }
        else if(Array.isArray(vnode.children)){
          vnode.children.forEach(child => {
            patch(null,child,el);
          });
        }

        if(vnode.props){
          for(const key in vnode.props){
            el.setAttribute(key,vnode.props[key])
          }
        }
        insert(el,container);
      }
      function patch(n1,n2,container){
        
        //n1不存在，意味着是挂载，则调用mountElement函数
        if(!n1){
          mountElement(n2,container);
        }
        else{
          //n1存在,意味着更新
        }
      }
      //客户端渲染
      function render(vnode,container){
        if(vnode){
          //新的vnode存在，将其于旧的vnode一起传给patch函数，进行打补丁
          patch(container._vnode,vnode,container);
        }
        else{
          if(container._vnode){
            container.innerHTML="";
          }
        }
        //将vnode存储到container._vnode下，后续渲染中的旧vnode
        container._vnode=vnode;
      }
      //服务器渲染
      function hydrate(vnode,container){

      }
      return {
        render,
        hydrate
      }
    }

    //使用============
    const renderer=createRenderer({
      createElement(tag){
        return document.createElement(tag);
      },
      setElementText(el,text){
        el.textContent=text;
      },
      insert(el,parent,anchor=null){
        parent.insertBefore(el,anchor);
      }
    });
    const vnode={
      type:"div",
      props:{
        id:"foo"
      },
      children:[
        {
          type:"p",
          children:"hello"
        }
      ]
    }
    const app=document.querySelector("#app");
 
    //首次渲染
    renderer.render(vnode,app);
    console.log("app",app)

  </script>
</body>
</html>